<?php

/**
 * Description of LoginController
 *
 * @author    Mon Zafra <monzee at gmail>
 * @copyright (c)2009 Mon Zafra
 * @license   http://monzee.wordpress.com/license New BSD
 * @version   $Id: LoginController.php 38 2009-02-18 17:12:39Z monzee $
 */
class User_LoginController extends Zend_Controller_Action
{
    public function postDispatch()
    {
        $flash = $this->getHelper('FlashMessenger');
        /* @var $flash Zend_Controller_Action_Helper_FlashMessenger */
        $flash->setNamespace('user');
        if ($flash->hasMessages()) {
            $this->view->messages = $flash->getMessages();
        }
    }

    public function indexAction()
    {
        $action = $this->_helper->url('submit');
        $this->view->form = new User_LoginForm(array('action' => $action));
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->flashMessenger('You have been logged out of the system.');
        $this->_redirect($this->_helper->url('index'));
    }

    public function submitAction()
    {
        $req = $this->getRequest();
        $action = $this->_helper->url('submit');
        $form = new User_LoginForm(array('action' => $action));
        if (!$req->isPost() || !$form->isValid($req->getPost())) {
            $this->view->form = $form;
            $this->render('index');
        } else {
            // TODO: check first and throw if there's no adapter
            $db = Zend_Db_Table::getDefaultAdapter();

            $configFile = $this->_helper->module('user')->pathTo('config.ini');
            $config = new Zend_Config_Ini($configFile, 'auth');
            $params = $config->db;

            $table = $params->get('table', 'members');
            $identity = $params->get('identity', 'username');
            $credential = $params->get('credential', 'password');
            $credTreatment = $params->get('treatment', '');

            $authAdapter = new Zend_Auth_Adapter_DbTable($db, $table, $identity, $credential, $credTreatment);
            $authAdapter->setIdentity($req->getPost('username'))
                        ->setCredential(md5($req->getPost('password')));
            $auth = Zend_Auth::getInstance();
            $res = $auth->authenticate($authAdapter);

            if ($res->isValid()) {
                $this->_helper->flashMessenger
                     ->setNamespace('user')
                     ->addMessage('You are now logged in.');

                $auth->getStorage()->write($authAdapter->getResultRowObject(null, 'password'));
            } else {
                $this->_helper->flashMessenger
                     ->setNamespace('user')
                     ->addMessage('Invalid credentials given.');

                $form->username->setValue($req->getPost('username'));
                $this->render('index');
            }

            $this->_redirect($this->_helper->url('index'));
        }
    }

}
